package Producer_Consumer_Blog;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-06
 * Time: 20:17
 */
class MyBlockingQueue{
    private int head = 0;
    private int tail = 0;
    private int useSize = 0;
    private final String[] array;

    public MyBlockingQueue(int capacity){
        this.array = new String[capacity];
    }

    public synchronized void put(String s) throws InterruptedException {
        while (useSize >= array.length){
            //队列满了,等待消费者消耗元素
            this.wait();
        }
        array[tail] = s;
        tail++;
        if (tail >= array.length){
            tail = 0;
        }
        useSize++;
        this.notify();
    }
    //删除第一个元素
    public synchronized String take() throws InterruptedException {
        while (useSize <= 0){
            //队列空了,等待生产者添加元素
            this.wait();
        }
        String ret = array[head];
        head++;
        if (head >= array.length){
            head = 0;
        }
        useSize--;
        this.notify();
        return ret;
    }
}

public class Producer_Consumer_Blog {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
        Thread thread1 = new Thread(()->{
            int n = 1;
            while (true){
                try {
                    queue.put(n + "");
                    System.out.println("生产元素n = " + n);
                    n++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread thread2 = new Thread(()->{
            while (true){
                try {
                    System.out.println("消费元素n = " + queue.take());
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread1.start();
        thread2.start();
    }
}
